<?php

namespace app\api\controller\Broadcast;

use app\api\controller\Common;
use app\api\Logic\Broadcast\BroadcastLogic;
use app\api\Logic\ManystoreShopLogic;
use app\api\Logic\Broadcast\BroadcastOrderLogic;
use app\api\model\BroadcastModel;
use app\api\model\BroadcastReplyModel;
use think\Exception;
use think\exception\DbException;

/**
 * 直播课程接口
 */
class Broadcast extends Common
{
    protected $noNeedLogin = ['*'];

    protected $broadcastLogic;
    protected $shopLogic;
    protected $broadcastOrderLogic;

    public function _initialize()
    {
        parent::_initialize();
        $this->broadcastLogic = new BroadcastLogic();
        $this->shopLogic = new ManystoreShopLogic();
        $this->broadcastOrderLogic = new BroadcastOrderLogic();
    }

    /**
     * 获取方式映射
     * @return array[]
     */
    protected function getTypeMap(){
        return [
            0 => ['type' => 0, 'name' => '不限方式'],
            1 => ['type' => 1, 'name' => '付费购买'],
            2 => ['type' => 2, 'name' => '免费'],
        ];
    }

    /**
     * 类型映射
     * @return array[]
     */
    protected function typeMap(){
        return [
            101 => ['type' => 101, 'name' => '直播中'],
            102 => ['type' => 102, 'name' => '待直播'],
            103 => ['type' => 103, 'name' => '回放'],
        ];
    }

    /**
     * 供前端调用，返回获取方式
     */
    public function getTypeAry(){
        $list = array_values($this->getTypeMap());
        if (!empty($list)) {
            $this->success('查询成功', $list);
        }
        $this->error('暂无数据');
    }

    /**
     * 供前端调用，返回类型
     */
    public function orderAry(){
        $list = array_values($this->typeMap());
        if (!empty($list)) {
            $this->success('查询成功', $list);
        }
        $this->error('暂无数据');
    }

    /**
     * 直播列表
     * @throws Exception
     * @throws DbException
     */
    public function getList(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            //校区ID
            $shopId = $param['shop_id'] ?? 0;
            //获取校区详情
            $shopInfo = $this->shopLogic->shopInfo($shopId);

            $query = BroadcastModel::where('shop_id',$shopId);
            //根据类型筛选
            if(isset($param['type']) && !empty($param['type'])){
                if(!isset($this->typeMap()[$param['type']])){
                    $this->error('类型不存在');
                }
                $query = $query->where('live_status',$param['type']);
            }
            //根据获取方式筛选
            if(isset($param['get_type']) && $param['get_type'] != 0){
                //付费购买
                if($param['get_type'] == 1){
                    $query = $query->where('price','>',0);
                }else if($param['get_type'] == 2){
                    $query = $query->where('price','<=',0);
                }
            }

            //获取列表
            $list = $query->field('id,shop_id,room_id,title,image,type,price,brand_id,view_type,share_type,user_ids')
                ->order('shop_id','asc')
                ->order('start_time','desc')
                ->select();
            $list = objToArray($list) ?? [];

            if(!empty($list)){
                //todo 用户是否在读状态，根据接口获取，这边先用默认值
                $isStudy = true;
                $res = [];
                foreach ($list as $val){
                    //当观看对象为学生时，需判断是否可见
                    if($val['view_type'] == 1){
                        //验证直播brand_id是否在校区brand_id内
                        if(!empty($shopInfo['brand_id'])){
                            $brandIds = explode(',',$shopInfo['brand_id']);
                            if(!in_array($val['brand_id'],$brandIds)){
                                continue;
                            }
                        }

                        $userIds = !empty($val['user_ids']) ? explode(',',$val['user_ids']) : [];
                        //在读学员可见
                        if($val['share_type'] == 2 && !$isStudy){
                            continue;
                        }else if($val['share_type'] == 3 && (empty($userIds) || !in_array($param['user_id'],$userIds))){
                            //指定学员可见
                            continue;
                        }
                    }
                    $res[] = $val;
                }

                $this->success('查询成功',$res);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 直播课程详情
     */
    public function info(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            if(!isset($param['broadcast_id']) || empty($param['broadcast_id'])){
                $this->error('直播课程ID必须');
            }

            //获取直播信息详情
            $info = $this->broadcastLogic->getInfo($param['shop_id'],$param['broadcast_id']);

            //获取是否已支付该课程
            $orderInfo = $this->broadcastOrderLogic->getOrderInfoByBroadcastId($param['shop_id'],$param['broadcast_id']);
            $info['is_buy'] = false;
            if(!empty($orderInfo) && $orderInfo['status'] == 1){
                $info['is_buy'] = true;
            }

            if(!empty($info)){
                $this->success('查询成功',$info);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 直播评论
     */
    public function reply(){
        if($this->request->isPost()){
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            //判断直播课程是否存在
            $exists = $this->broadcastLogic->exists($param['shop_id'],$param['broadcast_id']);
            if(!$exists){
                $this->error('直播信息不存在');
            }

            if(!isset($param['content']) || empty(trim($param['content']))){
                $this->error('评论内容不能为空');
            }
            if(strlen($param['content']) > 255){
                $this->error('评论内容太长');
            }

            //todo 用户身份，暂无接口，默认学员
            $userType = 3;
            $res = BroadcastReplyModel::insert([
                'shop_id' => $param['shop_id'],
                'broadcast_id' => $param['broadcast_id'],
                'user_type' => $userType,
                'user_id' => $param['user_id'],
                'content' => $param['content'],
                'createtime' => time()
            ]);

            if($res){
                $this->success('评论成功',$res);
            }
            $this->error('评论失败');
        }
        $this->error('请求错误');
    }

    /**
     * 直播评论列表
     * @throws DbException
     */
    public function replyList(){
        if($this->request->isPost()){
            $param = $this->request->param();
            //验证数据
            $param = $this->verifyData($param);

            //判断直播课程是否存在
            $exists = $this->broadcastLogic->exists($param['shop_id'],$param['broadcast_id']);
            if(!$exists){
                $this->error('直播信息不存在');
            }

            $list = BroadcastReplyModel::where('shop_id',$param['shop_id'])
                ->where('broadcast_id',$param['broadcast_id'])
                ->field('id,user_type,user_id,content,createtime')
                ->order('createtime','desc')
                ->paginate(PAGE_SIZE);
            $list = objToArray($list) ?? [];

            if(!empty($list)){
                $this->success('查询成功',$list);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }
}
